package com.bruce.ssm.base;

import com.bruce.ssm.entity.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.io.Serializable;
import java.util.List;

public class BaseDao extends BaseHibernateDao implements IBaseDao {

    public Object save(Object entity) {
        Transaction tx = getSession().beginTransaction();
        getSession().save(entity);
        tx.commit();
        closeSession();
        return null;
    }

    public boolean delete(Object entity) {
        Transaction tx = getSession().beginTransaction();
        Object en = getSession().merge(entity);
        getSession().delete(en);
        tx.commit();
        closeSession();
        return false;
    }

    public User deleteById(String id) {
        try {
            Transaction tx = getSession().beginTransaction();
            Object object = findOneIt(id);
            getSession().delete(object);
            tx.commit();
            closeSession();
            return (User) object;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean update(Object entity) {
        //先清除一下session
        closeSession();
        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        session.update(entity);
        transaction.commit();
        session.clear();
        return false;
    }

    public Object findOne(Serializable entityId) {
        return null;
    }

    public List getAll() {
        Session session = getSession();
        // 1、得到Query对象，并写入hql语句
        Query query = session.createQuery("from User");
//2、使用Query对象的list方法得到数据集合
        List<User> list = query.list();
        return list;
    }

    public Object findOneIt(String id) {
        return getSession().get(User.class, id);
    }
}
